const axios = require('axios')
const router = require('koa-router')()

// 引入数据库管理模块
const dbManager = require('../db/dbmanager')

router.get('/user/login', async (ctx, next) => {
  const code = ctx.query.code
  const appId = 'wx595a755c81dec853'
  const secret = '6bf2022ab353b867ba1f3e847347592f'
  const url = `https://api.weixin.qq.com/sns/jscode2session?appid=${appId}&secret=${secret}&js_code=${code}&grant_type=authorization_code`

  try {
    const res = await axios.get(url)
    const data = res.data
    const openid = data.openid // 获取到 openid

    // 先查询数据库中是否已经存在该openid
    const sqlSelect = 'SELECT * FROM user_info WHERE openid=?'
    const rows = await dbManager.query(sqlSelect, [openid])

    if (rows.length == 0) {
      // 如果不存在，则将 openid 存入数据库
      const sqlInsert = 'INSERT INTO user_info (openid) VALUES (?)'
      await dbManager.query(sqlInsert, [openid])
    }

    ctx.type = 'application/json'
    ctx.body = { code: 0, message: 'success', result: { openid } }
  } catch (error) {
    ctx.type = 'application/json'
    ctx.body = { code: -1, message: 'failed' }
  }
})

// 获取用户信息的路由
router.get('/user/info', async (ctx, next) => {
  const openid = ctx.request.query.openid // 获取openid

  // 根据openid从数据库中取出对应的用户信息
  const sql = 'SELECT * FROM user_info WHERE openid=?'
  const rows = await dbManager.query(sql, [openid])

  if (rows.length > 0) {
    const userInfo = rows[0]
    ctx.type = 'application/json'
    ctx.body = { code: 0, message: 'success', userInfo }
  } else {
    ctx.type = 'application/json'
    ctx.body = { code: -1, message: 'failed' }
  }
})

// 更新用户信息的路由
router.post('/user/update', async (ctx, next) => {
  const openid = ctx.request.body.openid // 获取openid
  const nickname = ctx.request.body.nickname // 获取昵称
  const gender = ctx.request.body.gender // 获取性别
  const birthday = ctx.request.body.birthday // 获取生日
  const avatarUrl = ctx.request.body.avatarUrl // 获取头像URL

  // 更新数据库中该用户对应的记录
  const sql = 'UPDATE user_info SET avatar=?,nickname=?, gender=?, birthday=? WHERE openid=?'
  const result = await dbManager.query(sql, [avatarUrl, nickname, gender, birthday, openid])

  // 根据更新结果返回相应的响应
  if (result.affectedRows > 0) {
    ctx.type = 'application/json'
    ctx.body = { code: 0, message: 'success' }
  } else {
    ctx.type = 'application/json'
    ctx.body = { code: -1, message: 'failed' }
  }
})

module.exports = router
